package config

import (
	"flag"
	"fmt"
	"gopkg.in/yaml.v2"
	"os"
	"regexp"
)

type Config struct {
	App        AppConfiguration `yaml:"app"`
	WhiteUrl   []string         `yaml:"whiteList"`
	ListenAddr string           `yaml:"listenAddr"`
	ForwardAdr string           `yaml:"forwardAdr"`
}

type AppConfiguration struct {
	Version string `yaml:"version"`
	Desc    string `yaml:"desc"`
}

var configFile = "./config.yaml"

func (config *Config) InitServer() {
	// 读取命令行参数
	var listenAddr, forwardAddr string
	listenAddr, forwardAddr, configPath := ParseArgs()
	//projectPath, err2 := os.Getwd()
	//if err2 != nil {
	//	fmt.Printf("read config.yaml failed: %s\n", err2.Error())
	//}
	//命令行中制定了配置文件路径，以命令行为准
	if &configPath != nil {
		configFile = configPath
	}
	fmt.Printf("config file path: %s\n", configFile)
	var file []byte
	file, err := os.ReadFile(configFile)
	if err != nil {
		fmt.Printf("read config.yaml failed: %s\n", err.Error())
	}
	err = yaml.Unmarshal(file, &config)
	if err != nil {
		fmt.Printf("Parsing configuration file error: %s\n", err.Error())
	}
	//监听端口及转发端口配置：如命令行参数指定了端接口，以命令行为准，没有则按照配置文件配置
	//判断命令行参数或配置文件是否指定了监听端口及转发端口，如都没有则退出程序
	if &listenAddr == nil && &config.ListenAddr != nil {
		listenAddr = config.ListenAddr
	}
	if &forwardAddr == nil && &config.ForwardAdr != nil {
		forwardAddr = config.ForwardAdr
	}
	if &forwardAddr == nil || &listenAddr == nil {
		fmt.Println("forwardAddr or listenAddr any blank")
		flag.Usage()
		os.Exit(0)
	}
}

func (config *Config) CheckWhiteUrl(url string) bool {
	for i := range config.WhiteUrl {
		whiteUrl := config.WhiteUrl[i]
		matched, err := regexp.MatchString(whiteUrl, url)
		if err != nil {
			return false
		}
		if matched == true {
			return true
		}
	}
	return false
}
